/**
 * @author zhouheng
 * @date 2022年03月11日 17:17
 */

package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.AuthContant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class CartInterceptor implements HandlerInterceptor {
    // 存放当前线程用户信息
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
        Object handler) throws Exception {
        // 判断缓存中是否存在登陆用户信息
        HttpSession session = request.getSession();
        System.out.println("cart服务："+ request.getRequestURI() + request.getRequestedSessionId());
        MemberRespVo memberRespVo = (MemberRespVo) session.getAttribute(AuthContant.LOGIN_USER);
        UserInfoTo userInfoTo = new UserInfoTo();
        if (memberRespVo != null) {
            userInfoTo.setUserId(memberRespVo.getId());
            userInfoTo.setUsername(memberRespVo.getUsername());
        }

        // 校验cookie中是否存在临时购物车的cookie信息
        for (Cookie cookie : request.getCookies()){
            if (StringUtils.equalsIgnoreCase(CartConstant.TEMP_USER_COOKIE_NAME, cookie.getName())) {
                // 校验成功
                userInfoTo.setUserKey(CartConstant.TEMP_USER_COOKIE_NAME);
                userInfoTo.setTempUser(true);
            }
        }

        // 如果是第一次添加购物车，还需要新建一个临时cookie-key
        if (StringUtils.isEmpty(userInfoTo.getUserKey()) && org.springframework.util.StringUtils.isEmpty(userInfoTo.getUserId())) {
            String uuid = UUID.randomUUID().toString().replace("-","");
            userInfoTo.setUserKey("GULI-" + uuid);//临时用户
        }

        threadLocal.set(userInfoTo);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIME_OUT);
            cookie.setDomain("gulimall.com");

            response.addCookie(cookie);
        }
    }
}
